<template>
  <div class="dept-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>院系管理</span>
          <el-button type="primary" @click="handleAdd" v-if="userStore.userInfo?.roleCode === 'admin'">
            <el-icon><Plus /></el-icon>
            新增院系
          </el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" :model="queryForm" class="search-form">
        <el-form-item label="关键词">
          <el-input
            v-model="queryForm.keyword"
            placeholder="院系名称/编码"
            clearable
            @clear="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table
        :data="tableData"
        v-loading="loading"
        style="width: 100%"
        border
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="deptCode" label="院系编码" width="120" />
        <el-table-column prop="deptName" label="院系名称" min-width="150" />
        <el-table-column prop="sort" label="排序" width="100" align="center" />
        <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="180" fixed="right" v-if="userStore.userInfo?.roleCode === 'admin'">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button link type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryForm.current"
          v-model:page-size="queryForm.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleQuery"
          @current-change="handleQuery"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="650px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="90px"
      >
        <el-form-item label="院系编码" prop="deptCode">
          <el-input 
            v-model="form.deptCode" 
            placeholder="请输入院系编码，如：CS、SE"
            clearable
            :disabled="!!form.id"
          >
            <template #prefix>
              <el-icon><Postcard /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="院系名称" prop="deptName">
          <el-input 
            v-model="form.deptName" 
            placeholder="请输入院系名称，如：计算机学院"
            clearable
          >
            <template #prefix>
              <el-icon><OfficeBuilding /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number 
            v-model="form.sort" 
            :min="0" 
            :max="999" 
            style="width: 100%"
            controls-position="right"
          />
          <div class="form-tip">数字越小越靠前</div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息（选填）"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false" size="large">
            <el-icon><Close /></el-icon>
            取消
          </el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading" size="large">
            <el-icon><Check /></el-icon>
            {{ form.id ? '保存' : '确定' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, Search, Refresh, OfficeBuilding, Postcard, Check, Close } from '@element-plus/icons-vue'
import { getDeptPage, addDept, updateDept, deleteDept } from '@/api/dept'
import { useUserStore } from '@/store/user'
import type { Dept } from '@/types'

const userStore = useUserStore()

// 查询表单
const queryForm = reactive({
  current: 1,
  size: 10,
  keyword: ''
})

// 表格数据
const tableData = ref<Dept[]>([])
const total = ref(0)
const loading = ref(false)

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('新增院系')
const formRef = ref<FormInstance>()
const submitLoading = ref(false)

// 表单数据
const form = reactive<Dept>({
  deptCode: '',
  deptName: '',
  sort: 0,
  remark: ''
})

// 表单验证规则
const rules: FormRules = {
  deptCode: [
    { required: true, message: '请输入院系编码', trigger: 'blur' },
    { min: 2, max: 20, message: '编码长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  deptName: [
    { required: true, message: '请输入院系名称', trigger: 'blur' },
    { min: 2, max: 50, message: '名称长度在 2 到 50 个字符', trigger: 'blur' }
  ]
}

// 查询列表
const getList = async () => {
  loading.value = true
  try {
    const data = await getDeptPage(queryForm)
    tableData.value = data.records
    total.value = data.total
  } catch (error) {
    console.error('获取院系列表失败', error)
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  queryForm.current = 1
  getList()
}

// 重置
const handleReset = () => {
  queryForm.keyword = ''
  handleQuery()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增院系'
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: Dept) => {
  dialogTitle.value = '编辑院系'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 删除
const handleDelete = async (row: Dept) => {
  try {
    await ElMessageBox.confirm('确定要删除该院系吗？', '提示', {
      type: 'warning'
    })
    await deleteDept(row.id!)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败', error)
    }
  }
}

// 提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (form.id) {
          await updateDept(form)
          ElMessage.success('更新成功')
        } else {
          await addDept(form)
          ElMessage.success('新增成功')
        }
        dialogVisible.value = false
        getList()
      } catch (error) {
        console.error('提交失败', error)
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 对话框关闭
const handleDialogClose = () => {
  formRef.value?.resetFields()
  Object.assign(form, {
    deptCode: '',
    deptName: '',
    sort: 0,
    remark: ''
  })
  delete form.id
}

onMounted(() => {
  getList()
})
</script>

<style scoped lang="scss">
.dept-container {
  padding: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .search-form {
    margin-bottom: 20px;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-input__prefix) {
  display: flex;
  align-items: center;
}
</style>

